<?php
namespace App\Controller;

use App\Helper\SeoHelper;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Hyperf\Utils\ApplicationContext;
use Psr\Http\Message\ResponseInterface;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use App\Service\ArticleService;
use App\Job\ArticleJob;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Coroutine;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;

/**
 * @Controller(prefix="api/petpal")
 */
class PetpalController
{
    protected $response;
    protected $queue;
    protected $loggerFactory;
    protected $logger;

    /**
     * @Inject
     * @var ValidatorFactoryInterface
     */
    protected $validatorFactory;

    public function __construct(
        HttpResponse $response,
        DriverFactory $driverFactory,
        LoggerFactory $loggerFactory,
        ValidatorFactoryInterface $validatorFactory
    ) {
        $this->response = $response;
        $this->queue = $driverFactory->get('default');
        $this->loggerFactory = $loggerFactory;
        $this->validatorFactory = $validatorFactory;
        $this->logger = $loggerFactory->get('article', 'article');
    }

    /**
     * @PostMapping(path="petpal-article")
     */
    public function petpalArticle(RequestInterface $request): ResponseInterface
    {
        $getData = $request->all();

        $validator = $this->validatorFactory->make($getData, [
            'webname' => 'required|string',
            'keywords' => 'required|string',
            'ids' => 'string',
            'extensions' => 'required|string',
        ], [
            'webname.required' => '参数 web 必填',
            'keywords.required' => '参数 keywords 必填',
            'extensions.required' => '参数 extensions 必填',
        ]);

        if ($validator->fails()) {
            return $this->response->json([
                'code' => 400,
                'msg' => $validator->errors()->first(),
            ]);
        }

        //  立即启动协程后台执行逻辑，不阻塞主流程
        Coroutine::create(function () use ($getData) {
            try {
                $conn = Db::connection(trim($getData['webname']));
                $batchSize = $getData['batch_size'] ?? 500;

                $baseQuery = "SELECT product_id FROM oc_product WHERE status = 1";
                $params = [];

                if (!empty($getData['ids'])) {
                    $ids = array_filter(array_map('intval', explode(',', $getData['ids'])));
                    if (!empty($ids)) {
                        $placeholders = implode(',', array_fill(0, count($ids), '?'));
                        $baseQuery .= " AND product_id IN ($placeholders)";
                        $params = $ids;
                    }
                }

                $countQuery = "SELECT COUNT(*) as total FROM oc_product WHERE status = 1";
                if (!empty($params)) {
                    $countQuery .= " AND product_id IN (" . implode(',', array_fill(0, count($params), '?')) . ")";
                }

                $totalCount = $conn->selectOne($countQuery, $params)->total ?? 0;

                $processed = 0;
                $page = 1;

                while ($processed < $totalCount) {
                    $query = $baseQuery . " LIMIT " . (($page - 1) * $batchSize) . ", " . $batchSize;
                    $cursor = $conn->cursor($query, $params);

                    foreach ($cursor as $product) {
                        $this->queue->push(new ArticleJob(
                            (int)$product->product_id,
                            $getData,
                            $this->loggerFactory
                        ));
                    }

                    $processed += $batchSize;
                    $page++;
                    usleep(100000); // 100毫秒间隔，防止压垮数据库或队列
                }

                $this->loggerFactory->get('petpal')->info("异步任务完成，总数：{$totalCount}");

            } catch (\Throwable $e) {
                $this->loggerFactory->get('petpal')->error('异步任务异常：' . $e->getMessage());
            }
        });

        // 立即返回响应，不等待协程执行结果
        return $this->response->json([
            'code' => 200,
            'msg' => '任务已接收，将异步分批推送到队列，请稍后查看结果。'
        ]);
    }

//    public function petpalArticle(RequestInterface $request): ResponseInterface
//    {
//        $getData = $request->all();
//
//        $validator = $this->validatorFactory->make($getData, [
//            'webname' => 'required|string',
//            'keywords' => 'required|string',
//            'ids' => 'string',
//            'extensions' => 'required|string',
//        ], [
//            'webname.required' => '参数 web 必填',
//            'webname.string' => '参数 web 必须为字符串',
//            'keywords.required' => '参数 keywords 必填',
//            'keywords.string' => '参数 keywords 必须为字符串',
//            'ids.string' => '参数 ids 必须为字符串',
//            'extensions.required' => '参数 extensions 必填',
//            'extensions.string' => '参数 extensions 必须为字符串',
//        ]);
//
//        if ($validator->fails()) {
//            return $this->response->json([
//                'code' => 400,
//                'msg' => $validator->errors()->first(),
//            ]);
//        }
//
//        try {
//            $conn = Db::connection(trim($getData['webname']));
//            $total = 0;
//            $batchSize = $getData['batch_size'] ?? 500; // 默认每批500条
//
//            // 基础查询
//            $baseQuery = "SELECT product_id FROM oc_product WHERE status = 1";
//            $params = [];
//
//            if (!empty($getData['ids'])) {
//                $ids = explode(',', $getData['ids']);
//                $ids = array_filter(array_map('intval', $ids));
//
//                if (empty($ids)) {
//                    return $this->response->json([
//                        'code' => 400,
//                        'msg' => '参数 ids 格式不正确，应为逗号分隔的数字',
//                    ]);
//                }
//
//                $placeholders = implode(',', array_fill(0, count($ids), '?'));
//                $baseQuery .= " AND product_id IN ($placeholders)";
//                $params = $ids;
//            }
//
//            $countQuery = "SELECT COUNT(*) as total FROM oc_product WHERE status = 1";
//            if (!empty($params)) {
//                $countQuery .= " AND product_id IN (".implode(',', array_fill(0, count($params), '?')).")";
//            }
//
//            $totalCount = $conn->selectOne($countQuery, $params)->total;
//
//            // 分批处理
//            $processed = 0;
//            $page = 1;
//
//            while ($processed < $totalCount) {
//                $query = $baseQuery . " LIMIT " . (($page - 1) * $batchSize) . ", " . $batchSize;
//
//                $cursor = $conn->cursor($query, $params);
//
//                foreach ($cursor as $product) {
//                    $this->queue->push(new ArticleJob(
//                        (int)$product->product_id,
//                        $getData,
//                        $this->loggerFactory
//                    ));
//                    $total++;
//                }
//
//                $processed += $batchSize;
//                $page++;
//
//                usleep(100000); // 100毫秒
//            }
//
//            return $this->response->json([
//                'code' => 200,
//                'msg' => "已推送{$total}条任务到队列，总商品数：{$totalCount}",
//                'data' => [
//                    'total' => $totalCount,
//                    'processed' => $total,
//                    'batch_size' => $batchSize,
//                ]
//            ]);
//        } catch (\InvalidArgumentException $e) {
//            return $this->response->json([
//                'code' => 400,
//                'msg' => $e->getMessage()
//            ]);
//        } catch (\Exception $e) {
//            return $this->response->json([
//                'code' => 500,
//                'msg' => $e->getMessage()
//            ]);
//        }
//    }
}
